package com.mzpai.web.controller;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gexin.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.model.StoreProductAttrValue;
import com.mzpai.product.model.StoreSeckill;
import com.mzpai.product.service.StoreProductAttrValueService;
import com.mzpai.product.service.StoreSeckillService;
import com.mzpai.product.vo.StoreSeckillQueryReqVo;
import com.mzpai.product.vo.StoreSeckillReqVo;
import com.mzpai.product.vo.StoreSeckillSaveVo;
import com.mzpai.product.vo.StoreSeckillVo;
import com.mzpai.util.DateUtil;
import com.mzpai.vo.ResponseVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(value = "门店秒杀商品发布接口")
@RestController
@RequestMapping("/storeSeckill")
public class StoreSeckillController extends BaseController {

	
	private static Logger log = LoggerFactory.getLogger(StoreSeckillController.class);
	
	@Autowired 
	private StoreSeckillService storeSeckillService;
	
	@Autowired 
	private StoreProductAttrValueService storeProductAttrValueService;
	
	
	@ApiOperation(value = "秒杀商品发布")
    @RequestMapping(value = "/pubSeckillProduct")
    public ResponseVo<Boolean> pubSeckillProduct(@RequestParam(value = "storeSeckillStr", required = true) String storeSeckillStr){
		
		log.info("msg1=开始秒杀商品发布,,method=pubSeckillProduct,,storeSeckillStr={}", storeSeckillStr);
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		StoreSeckillReqVo reqVo = JSONObject.parseObject(storeSeckillStr, StoreSeckillReqVo.class);
		List<StoreSeckillSaveVo> listStoreSeckill=reqVo.getListStoreSeckill();
		
		if(listStoreSeckill==null){
			ResponseVo<Boolean> resultVo=new ResponseVo<Boolean>();
			resultVo.setCode(ProductResExceptionCode.PUB_SECKILL_PRODUCT_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.PUB_SECKILL_PRODUCT_NULL.getMessage());
			resultVo.setResult(false);
			return resultVo;
		}
		
		List<StoreSeckill> storeSeckillList=buildStoreSeckillList(listStoreSeckill);
		try{
			storeSeckillService.insertBatch(storeSeckillList);
			resVo.setResult(true);
		} catch(Exception e) {
			logger.error("msg1= 发布秒杀商品信息异常， {}", e);
			resVo.setCode(-1);
			resVo.setMessage("操作失败!");
			resVo.setResult(false);
		}
    	return resVo;
	}
	
	
	
	
	private List<StoreSeckill> buildStoreSeckillList(List<StoreSeckillSaveVo> listStoreSeckill){
		
		List<StoreSeckill> list=new ArrayList<StoreSeckill>();
		for(StoreSeckillSaveVo vo:listStoreSeckill){
			StoreSeckill storeSeckill=new StoreSeckill();
			
			Integer productId=vo.getProductId();
		    String productName=vo.getProductName();
		    String image=vo.getImage();
		    Integer attrValueId=vo.getAttrValueId();
			Integer storeId=vo.getStoreId();
			String startTimeStr=vo.getStartTime();
			String stopTimeStr=vo.getStopTime();
			
			Date startTime=null;
			Date stopTime=null;
			try {
				startTime = DateUtil.parseByPattern(startTimeStr, DateUtil.DATE_HH_MM_SS);
				stopTime=DateUtil.parseByPattern(stopTimeStr, DateUtil.DATE_HH_MM_SS);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			BigDecimal seckillPrice=vo.getSeckillPrice();
			Integer personLimitNum=vo.getPersonLimitNum();
			Integer stock=vo.getStock();
			BigDecimal price=vo.getPrice();
			//设置值
			//查询规格 uniquie
			StoreProductAttrValue storeProductAttrValue=storeProductAttrValueService.queryByPrimaryId(attrValueId);
			if(storeProductAttrValue!=null){
				String unique=storeProductAttrValue.getUnique();
				storeSeckill.setUnique(unique);
			}
			storeSeckill.setProductId(productId);
			storeSeckill.setStoreId(storeId);
			storeSeckill.setProductAttrvalueId(attrValueId);
			storeSeckill.setProductName(productName);
			storeSeckill.setImage(image);
			storeSeckill.setStartTime(startTime);
			storeSeckill.setStopTime(stopTime);
			storeSeckill.setSeckillPrice(seckillPrice);
			storeSeckill.setPrice(price);
			storeSeckill.setOtPrice(price);
			storeSeckill.setIsDel(0);
			storeSeckill.setSales(0);
			storeSeckill.setIsShow(1);
			
			if(stock==null || stock == 0){
				storeSeckill.setStock(99999);
			}else{
				storeSeckill.setStock(stock);
			}
			
			if(personLimitNum==null || personLimitNum == 0) {
				storeSeckill.setNum(99999);
			} else {
				storeSeckill.setNum(personLimitNum);
			}
			
			storeSeckill.setAddTime(new Date());
			storeSeckill.setLockStockNum(0);
			storeSeckill.setStatus(1);
			list.add(storeSeckill);
		}
		return list;
	}
	
	/**
	 * 
	 * @param queryProductByPageStr
	 * @return
	 */
	@ApiOperation(value = "根据条件分页查询发布秒杀商品")
    @RequestMapping(value = "/queryStoreSeckillByPage",method = {RequestMethod. POST ,RequestMethod. GET })
    public ResponseVo<PageInfo<StoreSeckillVo>> queryStoreSeckillByPage(
    		@ApiParam(required = true, name = "queryStoreSeckillByPageStr", value = "入参为queryStoreSeckillByPageStr")
    		@RequestParam(value = "queryStoreSeckillByPageStr", required = true) String queryStoreSeckillByPageStr){
		
		log.info("msg1=开始根据条件分页查询发布秒杀商品数据,,method=queryStoreSeckillByPage,,reqVo={}",queryStoreSeckillByPageStr);
		StoreSeckillQueryReqVo storeProductReqVo = JSONObject.parseObject(queryStoreSeckillByPageStr, StoreSeckillQueryReqVo.class);
		
		Integer stroeId=storeProductReqVo.getStoreId();
		Integer pageNo=storeProductReqVo.getPageIndex();
		Integer pageSize=storeProductReqVo.getPageSize();
		if(stroeId==null){
			ResponseVo<PageInfo<StoreSeckillVo>> resVo=new ResponseVo<PageInfo<StoreSeckillVo>>();
			resVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			return resVo;
		}
		
		//根据顶层父类id查询所有叶子节点
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("storeId", stroeId);
		//删除 0未删除1已删除
		map.put("isDel", 0);
		PageInfo<StoreSeckillVo> storeSeckillVoPageInfo=storeSeckillService.getStoreSeckillByPage(map, pageNo, pageSize);
		List<StoreSeckillVo> listStoreSeckillVo=storeSeckillVoPageInfo.getList();
		
		if(listStoreSeckillVo!=null && !listStoreSeckillVo.isEmpty()){
			Date now=new Date();
			for(StoreSeckillVo vo:listStoreSeckillVo){
				String status=vo.getStatus();
				Integer id=vo.getId();
				if(status.equals("2")){
					vo.setStatus("3");
				}else{
					Date startTime=vo.getStartTime();
					Date stopTime=vo.getStopTime();
	                int compareToAfter=stopTime.compareTo(now);
	                if(compareToAfter>0){
	                	//startTime早于now，返回负数，可用于判断活动开始时间是否到了
	    		        int compareToBefore=startTime.compareTo(now);
	                    if(compareToBefore<0){
	                    	vo.setStatus("2");
	                    }else{
	                    	vo.setStatus("1");
	                    }
	                }else{
	                	vo.setStatus("3");
	                }
				}
			}
			//对list排序 秒杀商品开始状态 1:待开始,2:进行中,3: 已结束
			//进行中，待开始，已结束
			Collections.sort(listStoreSeckillVo, new Comparator<StoreSeckillVo>() {
	            @Override
	            public int compare(StoreSeckillVo o1, StoreSeckillVo o2) {
	                String status1 = o1.getStatus();
	                String status2 = o2.getStatus();
	                return status1.compareTo(status2);
	            }
	            
	        });
		}
		ResponseVo<PageInfo<StoreSeckillVo>> resVo=new ResponseVo<PageInfo<StoreSeckillVo>>();
		resVo.setResult(storeSeckillVoPageInfo);
		log.info("msg1=结束根据条件分页查询发布秒杀商品数据,,method=queryStoreSeckillByPage");
    	return resVo;
    }
	
	
	@ApiOperation(value = "点编辑进入编辑页面获取秒杀商品详情")
    @RequestMapping(value = "/queryStoreSeckillById", method = RequestMethod.POST)
    public ResponseVo<StoreSeckillVo> queryProductById(
    		@ApiParam(required = true, name = "id", value = "入参为主键id")
    		@RequestParam(value = "id", required = true) Integer id){
		
		log.info("msg1=开始编辑进入编辑页面获取秒杀商品详情,,method=queryStoreSeckillById,,id={}",id);
		
		StoreSeckill storeSeckill=storeSeckillService.queryByPrimaryId(id);
		
		StoreSeckillVo storeSeckillVo=null;
		if(storeSeckill!=null){
			storeSeckillVo=new StoreSeckillVo();
			storeSeckillVo.setId(id);
			storeSeckillVo.setProductId(storeSeckill.getProductId());
			storeSeckillVo.setProductName(storeSeckill.getProductName());
			storeSeckillVo.setAttrValueId(storeSeckill.getProductAttrvalueId());
			storeSeckillVo.setImage(storeSeckill.getImage());
			storeSeckillVo.setStoreId(storeSeckill.getStoreId());
			storeSeckillVo.setStartTime(storeSeckill.getStartTime());
			storeSeckillVo.setStopTime(storeSeckill.getStopTime());
			storeSeckillVo.setPrice(storeSeckill.getPrice());
			storeSeckillVo.setSeckillPrice(storeSeckill.getSeckillPrice());
			storeSeckillVo.setPersonLimitNum(storeSeckill.getNum());
			storeSeckillVo.setStock(storeSeckill.getStock());
			storeSeckillVo.setLockStockNum(storeSeckill.getLockStockNum());
		}
		ResponseVo<StoreSeckillVo> resVo=new ResponseVo<StoreSeckillVo>();
		resVo.setResult(storeSeckillVo);
		log.info("msg1=结束编辑进入编辑页面获取秒杀商品详情,,method=queryStoreSeckillById,,id={}",id);
		return resVo;
    }
	
	
	@ApiOperation(value = "秒杀编辑提交")
    @RequestMapping(value = "/updateStoreSeckill")
    public ResponseVo<Boolean> updateStoreSeckill(@ApiParam(required = true, name = "updateStoreSeckillStr", value = "入参为updateStoreSeckillStr")
    		@RequestParam(value = "updateStoreSeckillStr", required = true) String updateStoreSeckillStr){
		log.info("msg1=开始秒杀编辑提交,,method=updateStoreSeckill,,updateStoreSeckillStr={}",updateStoreSeckillStr);
		StoreSeckillSaveVo storeSeckillSaveVo = JSONObject.parseObject(updateStoreSeckillStr, StoreSeckillSaveVo.class);
		
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		
		Integer id = storeSeckillSaveVo.getId();
		if(id==null){
			resVo.setCode(ProductResExceptionCode.ID_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.ID_NULL.getMessage());
			return resVo;
		}
		Integer storeId=storeSeckillSaveVo.getStoreId();
		
		StoreSeckill storeSeckill=storeSeckillService.queryByPrimaryId(id);
		
		if(storeSeckill!=null){
			StoreSeckill updateStoreSeckill=buildStoreSeckillModel(storeSeckillSaveVo);
			storeSeckillService.update(updateStoreSeckill);
		}else{
			resVo.setCode(ProductResExceptionCode.PRODUCT_NOT_EXTEND_ERROR.getCode());
			resVo.setMessage(ProductResExceptionCode.PRODUCT_NOT_EXTEND_ERROR.getMessage());
			resVo.setResult(false);
			return resVo;
		}
		resVo.setCode(ProductResExceptionCode.SUCCESS.getCode());
		resVo.setMessage(ProductResExceptionCode.SUCCESS.getMessage());
		resVo.setResult(true);
		log.info("msg1=结束秒杀编辑提交,,method=updateStoreSeckill,,updateStoreSeckillStr={}");
    	return resVo;
    }
	
	private StoreSeckill buildStoreSeckillModel(StoreSeckillSaveVo storeSeckillSaveVo){
		StoreSeckill storeSeckill=null;
		if(storeSeckillSaveVo!=null){
			storeSeckill=new StoreSeckill();
//			Integer productId=storeSeckillSaveVo.getProductId();
//		    String productName=storeSeckillSaveVo.getProductName();
//		    String image=storeSeckillSaveVo.getImage();
//		    Integer attrValueId=storeSeckillSaveVo.getAttrValueId();
//			Integer storeId=storeSeckillSaveVo.getStoreId();
			Integer id=storeSeckillSaveVo.getId();
			
			String startTimeStr=storeSeckillSaveVo.getStartTime();
			String stopTimeStr=storeSeckillSaveVo.getStopTime();
			
			Date startTime = null;
			Date stopTime=null;
			try {
				startTime = DateUtil.parseByPattern(startTimeStr, DateUtil.DATE_HH_MM_SS);
				stopTime = DateUtil.parseByPattern(stopTimeStr, DateUtil.DATE_HH_MM_SS);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			BigDecimal seckillPrice=storeSeckillSaveVo.getSeckillPrice();
			Integer personLimitNum=storeSeckillSaveVo.getPersonLimitNum();
			Integer stock=storeSeckillSaveVo.getStock();
			BigDecimal price=storeSeckillSaveVo.getPrice();
			//设置值
			storeSeckill.setId(id);
			
//			storeSeckill.setProductId(productId);
//			storeSeckill.setStoreId(storeId);
//			storeSeckill.setProductAttrvalueId(attrValueId);
//			storeSeckill.setProductName(productName);
//			storeSeckill.setImage(image);
			storeSeckill.setStartTime(startTime);
			storeSeckill.setStopTime(stopTime);
			storeSeckill.setSeckillPrice(seckillPrice);
			storeSeckill.setPrice(price);
			storeSeckill.setNum(personLimitNum);
			storeSeckill.setStock(stock);
			storeSeckill.setAddTime(new Date());
			storeSeckill.setLockStockNum(0);
			storeSeckill.setStatus(1);
		}
		return storeSeckill;
	}
	
	
	@ApiOperation(value = "秒杀状态修改提交")
    @RequestMapping(value = "/updateSeckillState")
    public ResponseVo<Boolean> updateSeckillState(
    		@ApiParam(required = true, name = "Id", value = "主键id")
    		@RequestParam(value = "Id", required = true) Integer Id,
    		@ApiParam(required = true, name = "status", value = "商品秒杀状态,1:有效;2:无效")
    		@RequestParam(value = "status", required = true) Integer status){
		
		log.info("msg1=开始秒杀状态修改提交,,method=updateSeckillState,,Id={},status={}",Id,status);
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		
		if(Id==null){
			resVo.setCode(ProductResExceptionCode.ID_NULL.getCode());
			resVo.setMessage(ProductResExceptionCode.ID_NULL.getMessage());
			return resVo;
		}
		StoreSeckill storeSeckill=storeSeckillService.queryByPrimaryId(Id);
		if(storeSeckill!=null){
			StoreSeckill updateStoreSeckill=new StoreSeckill();
			updateStoreSeckill.setId(Id);
			updateStoreSeckill.setStatus(status);
			storeSeckillService.update(updateStoreSeckill);
		}else{
			resVo.setCode(ProductResExceptionCode.PRODUCT_NOT_EXTEND_ERROR.getCode());
			resVo.setMessage(ProductResExceptionCode.PRODUCT_NOT_EXTEND_ERROR.getMessage());
			resVo.setResult(false);
			return resVo;
		}
		resVo.setCode(ProductResExceptionCode.SUCCESS.getCode());
		resVo.setMessage(ProductResExceptionCode.SUCCESS.getMessage());
		resVo.setResult(true);
		log.info("msg1=结束秒杀状态修改提交,,method=updateSeckillState,,Id={},status={}",Id,status);
    	return resVo;
    }
	
	
	
	@ApiOperation(value = "删除秒杀活动")
    @RequestMapping(value = "/delStoreSeckillById", method = RequestMethod.POST)
    public ResponseVo<Boolean> delStoreSeckillById(
    		@ApiParam(required = true, name = "id", value = "入参为主键id")
    		@RequestParam(value = "id", required = true) Integer id){
		
		log.info("msg1=开始删除秒杀活动,,method=delStoreSeckillById,,id={}",id);
		Boolean result=true;
		StoreSeckill storeSeckill=storeSeckillService.queryByPrimaryId(id);
		if(storeSeckill!=null){
			StoreSeckill updateStoreSeckill=new StoreSeckill();
			updateStoreSeckill.setId(id);
			//非物理删除
			updateStoreSeckill.setIsDel(1);
			storeSeckillService.update(updateStoreSeckill);
		}
		ResponseVo<Boolean> resVo=new ResponseVo<Boolean>();
		resVo.setResult(result);
		log.info("msg1=结束删除秒杀活动,,method=delStoreSeckillById,,id={}",id);
		return resVo;
    }
	
	
	
}